//
//  DKButton.m
//  ButtonTest
//
//  Created by Alex on 15-2-11.
//  Copyright (c) 2015年 Alex. All rights reserved.
//

#import "DKButton.h"

@interface DKButton()


@end




@implementation DKButton

-(instancetype)init
{
    self=[super init];
    if(self)
    {
        [self initParam];
        [self initUI];
        [self refreshView];
    }
    return self;
}
-(instancetype)initWithFrame:(CGRect)frame
{
    self=[super initWithFrame:frame];
    if(self)
    {
        [self initParam];
        [self initUI];
        [self refreshView];
    }
    return self;
}

//初始化参数
-(void)initParam
{
    //按下的透明度初始化
    _pressAlpha=0.5;
    
    //图片部分初始化
    _imageTintColor=[UIColor whiteColor];
    _imageRenderingMode=DKButtonRenderingModeAlwaysTemplate;
    _image=nil;
    _imageSize=CGSizeMake(20, 20);
    
    //文字部分初始化
    _textColor=[UIColor whiteColor];
    _text=@"";
    _font=[UIFont systemFontOfSize:16.0f];
    
    //accessoryView初始化
    _accessoryView=nil;
    _accessorySize=CGSizeMake(15, 15);
    _accessoryRightGap=5;
    
    //文字与图片间的距离
    _imageTitleGap=5;
    
    //文字与图片的顺序
    _imagePosition=DKButtonImagePositionAtBegan;
    
    //三种颜色
    normalColor=[UIColor lightGrayColor];
    pressColor=nil;
    loadingColor=nil;
    
    //事件参数的初始化
    targetBegan=nil;
    selectBegan=nil;
    blockBegan=nil;
    
    targetPressing=nil;
    selectPressing=nil;
    blockPressing=nil;
    
    targetEnd=nil;
    selectEnd=nil;
    blockEnd=nil;
}

//构建UI
-(void)initUI
{
    [self setBackgroundColor:normalColor];
    
    //图片按钮
    _buttonImage=[[UIImageView alloc] init];
    //[_buttonImage setTintColor:_imageTintColor];
    [_buttonImage setContentMode:UIViewContentModeScaleAspectFit];
    [self addSubview:_buttonImage];
    
    //文字按钮
    _buttonTitle=[[UILabel alloc] init];
    [_buttonTitle setNumberOfLines:0];
    [_buttonTitle setFont:_font];
    [_buttonTitle setText:_text];
    [_buttonTitle setTextColor:_textColor];
    [self addSubview:_buttonTitle];
    
    //加载按钮
    _buttonLoading=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [_buttonLoading setHidesWhenStopped:YES];
    [self addSubview:_buttonLoading];
}

//动态调整页面
-(void)layoutSubviews
{
    [super layoutSubviews];
    [self refreshLayout];
}

//刷新布局
-(void)refreshLayout
{
    CGRect frame=self.frame;
    
    CGSize imageSizeTemp=_image==nil?CGSizeZero:_imageSize;
    CGFloat imageTitleGapTime=_image==nil?0:_imageTitleGap;
    //计算文字占的宽度
    NSDictionary *attributes = @{NSFontAttributeName: _font};
    _text=_text==nil?@"":_text;
    CGRect rect = [_text boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT)
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                  attributes:attributes
                                     context:nil];
    CGFloat textLength=MIN(frame.size.width-imageTitleGapTime-imageSizeTemp.width,
                             rect.size.width);
    
    
    //重新布局页面
    if(_imagePosition==DKButtonImagePositionAtBegan)
    {//图片在前
        _buttonImage.frame=CGRectMake((frame.size.width-imageSizeTemp.width-imageTitleGapTime-textLength)/2,
                                      (frame.size.height-imageSizeTemp.height)/2,
                                      imageSizeTemp.width,
                                      imageSizeTemp.height);
        _buttonTitle.frame=CGRectMake(_buttonImage.frame.origin.x+_buttonImage.frame.size.width+imageTitleGapTime,
                                      0,
                                      textLength,
                                      frame.size.height);
    }
    else
    {//图片在后
        _buttonTitle.frame=CGRectMake((frame.size.width-imageSizeTemp.width-imageTitleGapTime-textLength)/2,
                                      0,
                                      textLength,
                                      frame.size.height);
        _buttonImage.frame=CGRectMake(_buttonTitle.frame.origin.x+_buttonTitle.frame.size.width+imageTitleGapTime,
                                      (frame.size.height-imageSizeTemp.height)/2,
                                      imageSizeTemp.width,
                                      imageSizeTemp.height);
    }
    
    _buttonLoading.frame=CGRectMake(0, 0, frame.size.width, frame.size.height);
    
    
    if(_accessoryView!=nil)
    {
        _accessoryView.frame=CGRectMake(frame.size.width-_accessoryRightGap-_accessorySize.width,
                                        (frame.size.height-_accessorySize.height)/2,
                                        _accessorySize.width,
                                        _accessorySize.height);
    }
}

//刷新颜色显示
-(void)refreshView
{
    if(_imageRenderingMode==DKButtonRenderingModeAlwaysOriginal)
    {//渲染原图
        [_buttonImage setImage:[_image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    }
    else
    {
        [_buttonImage setImage:[_image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]];
    }
    
    //改变字体颜色
    [_buttonTitle setTextColor:_textColor];
    
    //改变背景色
    [self setBackgroundColor:normalColor];
}


//----------------------------------------------------------------------------
//图片的相应设置
-(void)setImageTintColor:(UIColor *)imageTintColor
{
    _imageTintColor=imageTintColor;
    [_buttonImage setTintColor:_imageTintColor];
    [self refreshView];
}

-(void)setImageRenderingMode:(DKButtonRenderingMode)imageRenderingMode
{
    _imageRenderingMode=imageRenderingMode;
    [self refreshView];
}

-(void)setImage:(UIImage *)image
{
    _image=image;
    [self refreshView];
    [self refreshLayout];
}

-(void)setImageSize:(CGSize)imageSize
{
    _imageSize=imageSize;
    [self refreshLayout];
}

//----------------------------------------------------------------------------
//文字等相应设置
-(void)setTextColor:(UIColor *)textColor
{
    _textColor=textColor;
    [self refreshView];
}

-(void)setText:(NSString *)text
{
    _text=text;
    [_buttonTitle setText:_text];
    [self refreshLayout];
}

-(void)setFont:(UIFont *)font
{
    _font=font;
    [_buttonTitle setFont:_font];
    [self refreshLayout];
}


//----------------------------------------------------------------------------
//设置颜色
-(void)setColor:(UIColor *)color ForState:(DKButtonState)state
{
    if(state==DKButtonStateLoading)
    {
        loadingColor=color;
    }
    else if(state==DKButtonStateNormal)
    {
        normalColor=color;
    }
    else if(state==DKButtonStatePressed)
    {
        pressColor=color;
    }
    [self refreshView];
}

//----------------------------------------------------------------------------
//文字与图片间的间距
-(void)setImageTitleGap:(CGFloat)imageTitleGap
{
    _imageTitleGap=imageTitleGap;
    [self refreshLayout];
}
//----------------------------------------------------------------------------
//accessoryView的相关设置
-(void)setAccessoryView:(UIView *)accessoryView
{
    if(_accessoryView!=nil)
    {
        [_accessoryView removeFromSuperview];
    }
    _accessoryView=accessoryView;
    [self addSubview:_accessoryView];
    [self refreshLayout];
}
-(void)setAccessorySize:(CGSize)accessorySize
{
    _accessorySize=accessorySize;
    [self refreshLayout];
}
-(void)setAccessoryRightGap:(CGFloat)accessoryRightGap
{
    _accessoryRightGap=accessoryRightGap;
    [self refreshLayout];
}

//----------------------------------------------------------------------------
//图片与文字的顺序
-(void)setImagePosition:(DKButtonImagePosition)imagePosition
{
    _imagePosition=imagePosition;
    [self refreshLayout];
}


//----------------------------------------------------------------------------
//开始动画与结束动画
-(void)startLoading
{
    [_buttonLoading startAnimating];
    [self setUserInteractionEnabled:NO];
    _buttonImage.hidden=YES;
    _buttonTitle.hidden=YES;
    if(loadingColor!=nil)
    {
        [self setBackgroundColor:loadingColor];
    }
    else
    {
        [_buttonLoading setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:0.5f]];
    }
}

-(void)endLoading
{
    [_buttonLoading stopAnimating];
    [self setUserInteractionEnabled:YES];
    _buttonImage.hidden=NO;
    _buttonTitle.hidden=NO;
    [self setBackgroundColor:normalColor];
}



//----------------------------------------------------------------------------
//两种点击事件的设置
-(void)addTarget:(id)targets Select:(SEL)selects ForEvent:(DKButtonEvent)events
{
    if(events==DKButtonEventPressedBegan)
    {
        targetBegan=targets;
        selectBegan=selects;
        blockBegan=nil;
    }
   /* else if(events==DKButtonEventPressing)
    {
        targetPressing=targets;
        selectPressing=selects;
        blockPressing=nil;
    }*/
    else
    {
        targetEnd=targets;
        selectEnd=selects;
        blockEnd=nil;
    }
}

-(void)addBlock:(DKButtonEventBlock)blocks ForEvent:(DKButtonEvent)events
{
    if(events==DKButtonEventPressedBegan)
    {
        targetBegan=nil;
        selectBegan=nil;
        blockBegan=blocks;
    }
   /* else if(events==DKButtonEventPressing)
    {
        targetPressing=nil;
        selectPressing=nil;
        blockPressing=blocks;
    }*/
    else
    {
        targetEnd=nil;
        selectEnd=nil;
        blockEnd=blocks;
    }
}


-(void)removeEvent:(DKButtonEvent)event
{
    if(event==DKButtonEventPressedBegan)
    {
        targetBegan=nil;
        selectBegan=nil;
        blockBegan=nil;
    }
    /* else if(events==DKButtonEventPressing)
     {
     targetPressing=nil;
     selectPressing=nil;
     blockPressing=nil;
     }*/
    else
    {
        targetEnd=nil;
        selectEnd=nil;
        blockEnd=nil;
    }
}

//----------------------------------------------------------------------------
//点击事件
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)events
{
    [self.layer removeAllAnimations];
    if(pressColor==nil)
    {
        [self setAlpha:0.5];
    }
    else
    {
        [self setBackgroundColor:pressColor];
    }
    

    if(blockBegan==nil)
    {
        if([targetBegan respondsToSelector:selectBegan])
        {
            [targetBegan performSelector:selectBegan withObject:self];
        }
    }
    else
    {
        blockBegan(self);
    }

}

-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [UIView animateKeyframesWithDuration:0.15
                                   delay:0
                                 options:UIViewKeyframeAnimationOptionAllowUserInteraction
                              animations:^(void)
     {
         if(pressColor==nil)
         {
             [self setAlpha:1.0];
         }
         else
         {
             [self setBackgroundColor:normalColor];
         }
     } completion:^(BOOL finished)
     {
     }];
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)events
{
    [UIView animateKeyframesWithDuration:0.15
                                   delay:0
                                 options:UIViewKeyframeAnimationOptionAllowUserInteraction
                              animations:^(void)
     {
         if(pressColor==nil)
         {
             [self setAlpha:1.0];
         }
         else
         {
             [self setBackgroundColor:normalColor];
         }
     }completion:^(BOOL finished)
     {

         if(blockEnd==nil)
         {
             if([targetEnd respondsToSelector:selectEnd])
             {
                 [targetEnd performSelector:selectEnd withObject:self];
             }
         }
         else
         {
             blockEnd(self);
         }

     }];
}

@end
